<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>星级评分原理和实现--第一种实现方式(改进代码)</title>
    <link rel="stylesheet" type="" href="css/main.css">
</head>
<body>
    <!-- 第一种实现方式 -->
    <ul id="rating" class="rating">
        <li class="rating_item" title="很不好"></li> 
        <li class="rating_item" title="不好"></li> 
        <li class="rating_item" title="一般"></li> 
        <li class="rating_item" title="好"></li> 
        <li class="rating_item" title="很好"></li> 
    </ul>
    
    <ul id="rating2" class="rating">
        <li class="rating_item" title="很不好"></li> 
        <li class="rating_item" title="不好"></li> 
        <li class="rating_item" title="一般"></li> 
        <li class="rating_item" title="好"></li> 
        <li class="rating_item" title="很好"></li> 
    </ul>

    <script src="js/jquery-3.2.1.min.js"></script>
    <script>
        // 改进代码2 => 闭包：自我执行函数
        var rating = (function(){

            //点亮
            var lightOn = function($item,num) {
                $item.each(function(index){
                    if(index < num) {
                        $(this).css('background-position','0 -65px');
                    } else {
                        $(this).css('background-position','0 0');
                    }
                });
            };

            // 改进代码3 => 代码复用:用函数传递参数
            var init = function(el,num) {
                var $rating = $(el),
                    $item = $rating.find('.rating_item');

                //初始化 
                lightOn($item,num);

                //事件绑定---改进代码1 => 事件委托：子元素委托给父元素(降低浏览器的性能需求)
                $rating.on('mouseover', '.rating_item', function() {
                    lightOn($item, $(this).index() + 1 );
                }).on('click', '.rating_item', function() {
                    num = $(this).index() +1;
                }).on('mouseout',function() {
                    lightOn($item,num);
                });

            };

            //改进代码3 => jQuery插件
            $.fn.extend({
                rating:function(num) {
                    return this.each(function() {
                        init(this,num)
                    });
                }
            });

            // 返回个对象
            return {
                init:init
            };

        })(); 

        rating.init('#rating',2);
        // rating.init('#rating2',3);

        //插件调用
        $('#rating2').rating(4)

    </script>
</body>
</html>